#!/bin/bash

version=5.0.9
user=redis
port=6379
password=123456
base_dir=/data/redis
data_dir=${base_dir}/data
pakeage_dir=${base_dir}/package
install_dir=${base_dir}/install
base_dir_sed="\/data\/redis"
data_dir_sed="${base_dir_sed}\/data"

yum install gcc-c++ wget -y
mkdir -p ${data_dir} ${pakeage_dir} ${install_dir}
useradd -s /sbin/nologin ${user}
cd ${pakeage_dir} && wget -t 0 -c https://download.redis.io/releases/redis-${version}.tar.gz
tar -xf redis-${version}.tar.gz
cd redis-${version}
make && make PREFIX=${install_dir} install
cp redis.conf ${data_dir}/
# 编辑配置文件
sed -i 's/^bind\(.*\)/bind 0.0.0.0/' /data/redis/data/redis.conf
sed -i 's/^protected-mode\(.*\)/protected-mode yes/' /data/redis/data/redis.conf
sed -i "s/^port\(.*\)/port ${port}/" /data/redis/data/redis.conf
sed -i 's/^daemonize\(.*\)/daemonize yes/' /data/redis/data/redis.conf
sed -i "s/^pidfile\(.*\)/pidfile ${data_dir_sed}\/redis.pid/" /data/redis/data/redis.conf
sed -i 's/^loglevel\(.*\)/loglevel verbose/' /data/redis/data/redis.conf
sed -i "s/^logfile\(.*\)/logfile ${data_dir_sed}\/redis_err_log/" /data/redis/data/redis.conf
sed -i "s/^dir\(.*\)/dir ${data_dir_sed}\//" /data/redis/data/redis.conf
sed -i "s/^# requirepass\(.*\)/requirepass ${password}/" /data/redis/data/redis.conf

chown -R ${user}.${user} ${base_dir}

cat > /usr/lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=/data/redis/install/bin/redis-server /data/redis/data/redis.conf --supervised systemd
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
Type=forking
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload && systemctl start redis && systemctl enable redis

echo -e "export REDIS_HOME=${install_dir}" >  /etc/profile.d/redis.sh
source /etc/profile.d/redis.sh
echo -e "export PATH=${PATH}:${REDIS_HOME}/bin" >>  /etc/profile.d/redis.sh
echo -e "\033[31m请执行：source /etc/profile.d/redis.sh\033[0m"